package com.ctsi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctsi.common.util.Search;
import com.ctsi.core.common.entity.LoginEmpInfo;
import com.ctsi.core.common.entity.LoginUser;
import com.ctsi.core.common.exception.MarsException;
import com.ctsi.core.common.exception.ServiceException;
import com.ctsi.core.common.util.$;
import com.ctsi.core.common.util.IPUtil;
import com.ctsi.core.common.util.RequestHolder;
import com.ctsi.core.common.util.network.UaUtil;
import com.ctsi.core.database.util.PageUtil;
import com.ctsi.core.web.enums.AdminTypeEnum;
import com.ctsi.system.constant.DictConstant;
import com.ctsi.system.dto.UserInfo;
import com.ctsi.system.entity.ZsjUser;
import com.ctsi.system.enums.SystemExceptionEnum;
import com.ctsi.system.enums.UserExceptionEnum;
import com.ctsi.system.mapper.ZsjUserMapper;
import com.ctsi.system.service.*;
import com.ctsi.uaa.enums.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 电信用户管理 服务实现类
 * </p>
 *
 * @author fxd
 * @date 2022-03-01 16:51:32
 */
@Service
public class ZsjUserServiceImpl extends ServiceImpl<ZsjUserMapper, ZsjUser> implements IZsjUserService {
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IMenuService menuService;
	@Autowired
	private IEmpService empService;
	@Autowired
	private IAppService appService;

	@Override
	public IPage<ZsjUser> listPage(ZsjUser zsjuser, Search search) {
		boolean isKeyword = $.isNotBlank(search.getKeyword());
		QueryWrapper<ZsjUser> queryWrapper = Wrappers.query();
		// 多条件模糊查询
		if (isKeyword) {
			queryWrapper.and(wrapper ->
					wrapper
							// 查询名称
							.like("zsj_user_info.staff_name", search.getKeyword()));
		}
		Long orgId = search.getOrgId();
		queryWrapper.eq($.isNotNull(zsjuser.getStatusCd()), "zsj_user_info.status_cd", zsjuser.getStatusCd());
		queryWrapper.lambda().orderByDesc(ZsjUser::getCreateDate);
		// 根据左侧点击过滤组织ID
		if ($.isNotEmpty(orgId)) {
			queryWrapper.and(q -> q.eq("zsj_user_info.org_id", orgId));
		}
		return this.baseMapper.page(PageUtil.getPage(search), queryWrapper);
	}

	@Override
	public UserInfo getUserInfo(ZsjUser user) {
		if ($.isEmpty(user)) {
			return new UserInfo().setErrorMessage(UserExceptionEnum.USER_NOT_EXIST.getMessage());
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setZsjuser(user);
		List<Dict> roles = roleService.getLoginRoles(user.getStaffId(), UserType.TELECOM.getType());
		if ($.isEmpty(roles)) {
			return new UserInfo().setErrorMessage(SystemExceptionEnum.ROLE_NOT_EXIST.getMessage());
		}
		List<Long> roleList = roles.stream().map(dict -> $.toLong(dict.get(DictConstant.ID))).collect(Collectors.toList());
		// 权限信息
		List<String> permissions = menuService.getLoginPermissions(user.getStaffId(),UserType.TELECOM.getType());
		userInfo.setRoleIds(roleList);
		userInfo.setPermissions(permissions);
		return userInfo;
	}

	@Override
	public LoginUser getLoginUserByRequest(Long userId, HttpServletRequest request) {
		ZsjUser user = this.getById(userId);
		// 构造LoginUser
//		LoginUser loginUser = $.copy(user, LoginUser.class);
		LoginUser loginUser = new LoginUser();
		loginUser.setId(user.getStaffId());
		loginUser.setAccount(user.getStaffAccount());
		loginUser.setName(user.getStaffName());
		loginUser.setAdminType(AdminTypeEnum.NONE.getCode());
		loginUser.setPhone(user.getMobilePhone());
		if ($.isNull(loginUser)) {
			throw new MarsException(UserExceptionEnum.USER_NOT_EXIST);
		}
		if ($.isNotNull(request)) {
			loginUser.setLastLoginIp(RequestHolder.getHttpServletRequestIpAddress());
			loginUser.setLastLoginTime(DateTime.now().toString());
			loginUser.setLastLoginAddress(IPUtil.getCityInfo(loginUser.getLastLoginIp()));
			loginUser.setLastLoginOs(UaUtil.getOs(request));
			loginUser.setLastLoginBrowser(UaUtil.getBrowser(request));
			// 更新用户数据增加登录IP和登录时间
//			user.setLastLoginIp(loginUser.getLastLoginIp());
//			user.setLastLoginTime(LocalDateTime.now());
//			updateById(user);

			// 员工信息
			LoginEmpInfo loginEmpInfo = empService.getLoginEmpInfo(userId);
			loginUser.setLoginEmpInfo(loginEmpInfo);

			// 角色信息
			List<Dict> roles = roleService.getLoginRoles(userId,UserType.TELECOM.getType());
			loginUser.setRoles(roles);

			// 权限信息
			List<String> permissions = menuService.getLoginPermissions(userId,UserType.TELECOM.getType());
			loginUser.setPermissions(permissions);

			// 具备应用信息（多系统，默认激活一个，可根据系统切换菜单）,返回的结果中第一个为激活的系统
			List<Dict> apps = appService.getLoginApps(userId,UserType.TELECOM.getType());
			loginUser.setApps(apps);

			// 如果根本没有应用信息，则没有菜单信息
			if (ObjectUtil.isEmpty(apps)) {
				loginUser.setMenus(CollectionUtil.newArrayList());
			} else {
				//AntDesign菜单信息，根据人获取，用于登录后展示菜单树，默认获取默认激活的系统的菜单
				String defaultActiveAppCode = apps.get(0).getStr(DictConstant.CODE);
				loginUser.setMenus(menuService.getLoginMenusAntDesign(userId, defaultActiveAppCode,UserType.TELECOM.getType()));
			}
			// 如果开启了多租户功能，则设置当前登录用户的租户标识
			// 待补充

		} else {
			throw new ServiceException("当前请求数据为空！");
		}
		return loginUser;
	}
}
